# -*- coding: utf8 -*-
from django.shortcuts import render
from django.http import HttpResponse
from django.conf import settings
import requests, os
import json
import hashlib, base64, hmac
import sys

info = sys.version_info
if info[0] < 3:
    is_python3 = False
else:
    is_python3 = True

app_key = '203868392'
secret = 'JxHtCyN79UDC0AdLUzXvARshI1lyUtwn'
# file_name = url
# print(file_name)
stage = 'RELEASE'  # 正式环境
# stage = 'TEST' # 测试环境
# 人像抠图接口
def params_of_portrait_matting(photo_base64, photo_type):
    print('测试人像抠图接口 ...')
    host = 'https://aliapi.aisegment.com'
    uri = '/segment/matting'
    return host, uri, {
        'photo': photo_base64,
        'type': photo_type,
        'face_required': 0  # 可选，检测是否必须带有人脸才进行抠图处理，0为检测，1为不检测，默认为0,设置这个参数后，可能导致人体背影无法抠图
    }


# 普通物品扣图接口
def params_of_object_matting(photo_base64):
    print('测试普通物品扣图接口 ...')
    host = 'https://objseg.market.alicloudapi.com'
    uri = '/commonseg/rgba'
    return host, uri, {
        'photo': photo_base64
    }


# 头像抠图接口
def params_of_head(photo_base64, photo_type):
    print('测试头像抠图接口 ...')
    host = 'https://person.market.alicloudapi.com'
    uri = '/segment/person/headrgba'  # 头像抠图返回透明PNG图
    # uri = '/segment/person/head'   # 头像抠图返回alpha图
    # uri = '/segment/person/headborder' # 头像抠图返回带白边的透明PNG图
    return host, uri, {
        'photo': photo_base64,
        'type': photo_type,
        'face_required': 0,  # 可选，检测是否必须带有人脸才进行抠图处理，0为检测，1为不检测，默认为0
        'border_ratio': 0.3,  # 可选，仅带白边接口可用，
        # 在头像边缘增加白边（或者其他颜色）宽度，取值为0-0.5，
        # 这个宽度是相对于图片宽度和高度最大值的比例，
        # 比如原图尺寸为640x480，border_ratio为0.2，
        # 则添加的白边的宽度为：max(640,480) * 0.2 = 96个像素
        'margin_color': '#ff0000'  # 可选，仅带白边接口可用，
        # 在头像边缘增加边框的颜色，默认为白色
    }


# 证件照制作接口
def params_of_idphoto(photo_base64, photo_type, nid, color):
    print('测试证件照制作接口 ...')
    host = 'https://alidphoto.aisegment.com'
    uri = '/idphoto/make'
    return host, uri, {
        'photo': photo_base64,
        'type': photo_type,
        'spec': nid,
        'bk': color,
        "beauty_degree": 1.0  # 可选，美颜级别，取值1.0-5.0
    }


# 商品裁剪接口
def params_of_crop(photo_base64):
    print('测试商品裁剪接口 ...')
    host = 'https://ecimage.market.alicloudapi.com'
    uri = '/commodity/crop'
    return host, uri, {
        'photo': photo_base64,
        'output_size': [600, 800],  #
        'object_ratio': 0.9
    }


def test_segment(request):
    if request.method == 'GET':
        return render(request, 'index.html')
    else:
        nid = request.POST.get('nid')
        color = request.POST.get('color')
        img = request.FILES.get('picture')
        # print('begin')
        # print(nid,img,color)
        # print('end')

        media_root = settings.MEDIA_ROOT  # media
        allow_upload = settings.ALLOW_UPLOAD  # ALLOW_UPLOAD
        path = media_root + '/upload'
        if not os.path.exists(path):  # 判断路径是否存在
            os.makedirs(path)  # 创建此路径
        if img.name.split('.')[-1] not in allow_upload:
            return HttpResponse('fail')

        # 保存上传文件夹
        with open(path + '/' + img.name, 'wb') as f:
            for c in img.chunks():  # 相当于切片
                f.write(c)
        url = path + '/' + img.name

    with open(url, 'rb') as fp:
        photo_base64 = base64.b64encode(fp.read())
    if is_python3:
        photo_base64 = photo_base64.decode('utf8')

    _, photo_type = os.path.splitext(url)
    photo_type = photo_type.lstrip('.')
    host, uri, body_json = params_of_idphoto(photo_base64, photo_type, nid, color)
    api = host + uri
    body = json.dumps(body_json)
    md5lib = hashlib.md5()
    if is_python3:
        md5lib.update(body.encode('utf8'))
    else:
        md5lib.update(body)
    body_md5 = md5lib.digest()
    body_md5 = base64.b64encode(body_md5)
    if is_python3:
        body_md5 = body_md5.decode('utf8')

    method = 'POST'
    accept = 'application/json'
    content_type = 'application/octet-stream; charset=utf-8'
    date_str = ''
    headers = ''

    string_to_sign = method + '\n' \
                     + accept + '\n' \
                     + body_md5 + '\n' \
                     + content_type + '\n' \
                     + date_str + '\n' \
                     + headers \
                     + uri
    if is_python3:
        signed = hmac.new(secret.encode('utf8'),
                          string_to_sign.encode('utf8'),
                          digestmod=hashlib.sha256).digest()
    else:
        signed = hmac.new(secret, string_to_sign, digestmod=hashlib.sha256).digest()
    signed = base64.b64encode(signed)
    if is_python3:
        signed = signed.decode('utf8')

    headers = {
        'Accept': accept,
        'Content-MD5': body_md5,
        'Content-Type': content_type,
        'X-Ca-Key': app_key,
        'X-Ca-Stage': stage,
        'X-Ca-Signature': signed
    }
    # print signed

    resp = requests.post(api, data=body, headers=headers)
    try:
        res = resp.content
        res = json.loads(res)
        img_url = res['data']['result']
        print('res:', res)
        if str(res['status']) == '0':
            print('成功!')
            return img_url
        else:
            print('失败!')
    except:
        print('failed parse:', resp)


if __name__ == "__main__":
    test_segment()
    print('开始执行换底程序')
